import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import bank_dialog
import styles

class BankSystem(tk.Tk):
    """银行业务管理系统主类"""

    def __init__(self, db_connection):
        super().__init__()
        self.title("银行业务管理系统")
        self.geometry("1000x700")
        self.configure(bg="#ffffff")

        # 当前用户信息
        self.user_type = None
        self.card_id = None
        self.current_balance = 0.0
        self.card_status = "正常"  # 记录银行卡状态

        # 数据库连接
        self.db_connection = db_connection

        # 创建登录界面
        self.create_login_ui()

        # 应用样式
        styles.apply_styles()

        # 状态栏
        self.status_var = tk.StringVar(value="就绪")
        self.status_bar = ttk.Label(self, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    def create_login_ui(self):
        """创建登录界面"""
        self.login_frame = ttk.Frame(self, padding=20, style="White.TFrame")
        self.login_frame.pack(expand=True, anchor=tk.CENTER)
        self.login_frame.configure(style="White.TFrame")

        # 标题
        title_label = ttk.Label(self.login_frame, text="银行业务管理系统",
                                font=("Microsoft YaHei", 24, "bold"), foreground="#1890ff",
                                background="#ffffff")
        title_label.pack(pady=20)

        # 登录表单
        form_frame = ttk.Frame(self.login_frame, style="White.TFrame")  # 表单框架背景为白色
        form_frame.pack(pady=30, padx=50, fill=tk.X)

        # 用户类型
        user_type_label = ttk.Label(form_frame, text="用户类型:", background="#ffffff")  # 设置标签背景为白色
        user_type_label.grid(row=0, column=0, padx=10, pady=10, sticky=tk.E)

        self.user_type_var = tk.StringVar(value="客户")
        user_type_combo = ttk.Combobox(form_frame, textvariable=self.user_type_var,
                                       values=["管理员", "客户"], state="readonly", width=18)
        user_type_combo.grid(row=0, column=1, padx=10, pady=10, sticky=tk.W)

        # 卡号
        card_id_label = ttk.Label(form_frame, text="卡号:", background="#ffffff")  # 设置标签背景为白色
        card_id_label.grid(row=1, column=0, padx=10, pady=10, sticky=tk.E)

        self.card_id_var = tk.StringVar()
        card_id_entry = ttk.Entry(form_frame, textvariable=self.card_id_var, width=20)
        card_id_entry.grid(row=1, column=1, padx=10, pady=10, sticky=tk.W)

        # 密码
        password_label = ttk.Label(form_frame, text="密码:", background="#ffffff")  # 设置标签背景为白色
        password_label.grid(row=2, column=0, padx=10, pady=10, sticky=tk.E)

        self.password_var = tk.StringVar()
        password_entry = ttk.Entry(form_frame, textvariable=self.password_var, show="*", width=20)
        password_entry.grid(row=2, column=1, padx=10, pady=10, sticky=tk.W)

        # 登录按钮
        login_btn = ttk.Button(self.login_frame, text="登 录", width=15,
                               command=self.authenticate, style="Accent.TButton")
        login_btn.pack(pady=20)

        for widget in self.login_frame.winfo_children():
            if isinstance(widget, ttk.Frame):
                widget.configure(style="White.TFrame")
            elif hasattr(widget, 'configure'):
                try:
                    widget.configure(background="#ffffff")
                except:
                    pass

    def authenticate(self):
        """用户认证"""
        user_type = self.user_type_var.get()
        card_id = self.card_id_var.get()
        password = self.password_var.get()

        if not card_id or not password:
            messagebox.showwarning("输入错误", "卡号和密码不能为空！")
            return

        if user_type == "管理员":
            if card_id == "admin" and password == "admin123":
                self.user_type = "admin"
                self.card_id = "admin"
                self.show_main_ui()
            else:
                messagebox.showwarning("登录失败", "管理员账号或密码错误！")
        else:
            try:
                cursor = self.db_connection.cursor()
                cursor.execute("SELECT * FROM cardinfo WHERE cardID = %s AND pass = %s",
                              (card_id, password))
                result = cursor.fetchone()
                cursor.close()

                if result:
                    self.user_type = "customer"
                    self.card_id = card_id
                    self.current_balance = float(result[5])  # 余额在第6个位置
                    self.card_status = "已挂失" if result[7] == "是" else "正常"
                    self.show_main_ui()
                else:
                    messagebox.showwarning("登录失败", "卡号或密码错误！")
            except Exception as e:
                messagebox.showerror("数据库错误", f"数据库查询失败: {str(e)}")

    def show_main_ui(self):
        """主界面"""
        self.login_frame.pack_forget()

        # 创建主框架
        self.main_frame = ttk.Frame(self)
        self.main_frame.pack(expand=True, fill=tk.BOTH)

        # 创建顶部工具栏
        toolbar = ttk.Frame(self.main_frame)
        toolbar.pack(fill=tk.X, padx=10, pady=5)

        # 注销按钮
        logout_btn = ttk.Button(toolbar, text="注 销", width=10,
                                command=self.logout, style="Accent.TButton")
        logout_btn.pack(side=tk.RIGHT, padx=5)

        # 用户信息
        user_info = f"当前用户: {'管理员' if self.user_type == 'admin' else '客户'} - {self.card_id}"
        if self.user_type == "customer":
            user_info += f" | 状态: {self.card_status}"
        ttk.Label(toolbar, text=user_info, font=("Microsoft YaHei", 10)).pack(side=tk.LEFT)

        self.tabs = ttk.Notebook(self.main_frame)
        self.tabs.pack(expand=True, fill=tk.BOTH, padx=10, pady=5)

        if self.user_type == "admin":
            self.create_admin_tabs()
        else:
            self.create_customer_tabs()

    def create_admin_tabs(self):
        """管理员选项"""
        # 客户管理
        customer_tab = ttk.Frame(self.tabs)
        self.create_customer_management(customer_tab)
        self.tabs.add(customer_tab, text="客户管理")

        # 银行卡管理
        card_tab = ttk.Frame(self.tabs)
        self.create_card_management(card_tab)
        self.tabs.add(card_tab, text="银行卡管理")

        # 存款业务管理
        deposit_tab = ttk.Frame(self.tabs)
        self.create_deposit_management(deposit_tab)
        self.tabs.add(deposit_tab, text="存款业务管理")

        # 交易管理
        transaction_tab = ttk.Frame(self.tabs)
        self.create_transaction_management(transaction_tab)
        self.tabs.add(transaction_tab, text="交易管理")

    def create_customer_tabs(self):
        """客户选项"""
        # 账户操作
        account_tab = ttk.Frame(self.tabs)
        self.create_account_operations(account_tab)
        self.tabs.add(account_tab, text="账户操作")

        # 交易查询
        transaction_tab = ttk.Frame(self.tabs)
        self.create_transaction_query(transaction_tab)
        self.tabs.add(transaction_tab, text="交易查询")

        # 账户管理
        manage_tab = ttk.Frame(self.tabs)
        self.create_account_management(manage_tab)
        self.tabs.add(manage_tab, text="账户管理")

    def create_customer_management(self, parent):
        """客户管理"""
        # 顶部按钮
        btn_frame = ttk.Frame(parent)
        btn_frame.pack(fill=tk.X, padx=10, pady=5)

        ttk.Button(btn_frame, text="添加客户", width=10, command=self.add_customer, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="修改信息", width=10, command=self.edit_customer, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="删除客户", width=10, command=self.delete_customer, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="导出CSV", width=10, command=self.export_customer_csv, style="Accent.TButton").pack(side=tk.LEFT, padx=5)

        # 查询框
        search_frame = ttk.Frame(parent)
        search_frame.pack(fill=tk.X, padx=10, pady=5)

        ttk.Label(search_frame, text="客户ID:").pack(side=tk.LEFT, padx=5)
        self.customer_id_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.customer_id_var, width=15).pack(side=tk.LEFT, padx=5)

        ttk.Label(search_frame, text="姓名:").pack(side=tk.LEFT, padx=5)
        self.customer_name_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.customer_name_var, width=15).pack(side=tk.LEFT, padx=5)

        ttk.Label(search_frame, text="身份证号:").pack(side=tk.LEFT, padx=5)
        self.customer_pid_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.customer_pid_var, width=15).pack(side=tk.LEFT, padx=5)

        ttk.Label(search_frame, text="年龄范围:").pack(side=tk.LEFT, padx=5)
        self.min_age_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.min_age_var, width=5).pack(side=tk.LEFT, padx=5)
        ttk.Label(search_frame, text="至").pack(side=tk.LEFT, padx=5)
        self.max_age_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.max_age_var, width=5).pack(side=tk.LEFT, padx=5)

        ttk.Button(search_frame, text="查 询", width=10, command=self.search_customer, style="Accent.TButton").pack(
            side=tk.LEFT, padx=5)

        # 表格
        table_frame = ttk.Frame(parent)
        table_frame.pack(expand=True, fill=tk.BOTH, padx=10, pady=5)

        columns = ("customerID", "customerName", "PID", "telephone", "address")
        self.customer_table = ttk.Treeview(table_frame, columns=columns, show="headings")

        self.customer_table.heading("customerID", text="客户ID")
        self.customer_table.heading("customerName", text="姓名")
        self.customer_table.heading("PID", text="身份证号")
        self.customer_table.heading("telephone", text="联系电话")
        self.customer_table.heading("address", text="联系地址")

        self.customer_table.column("customerID", width=80, anchor=tk.CENTER)
        self.customer_table.column("customerName", width=100, anchor=tk.CENTER)
        self.customer_table.column("PID", width=180, anchor=tk.CENTER)
        self.customer_table.column("telephone", width=120, anchor=tk.CENTER)
        self.customer_table.column("address", width=250, anchor=tk.CENTER)

        # 添加滚动条
        scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=self.customer_table.yview)
        self.customer_table.configure(yscroll=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.customer_table.pack(expand=True, fill=tk.BOTH)

        # 加载数据
        self.load_customer_data()

    def search_customer(self):
        """查询客户"""
        customer_id = self.customer_id_var.get()
        name = self.customer_name_var.get()
        pid = self.customer_pid_var.get()
        min_age = self.min_age_var.get()
        max_age = self.max_age_var.get()

        query = "SELECT * FROM userinfo WHERE 1=1"
        params = []

        if customer_id:
            query += " AND customerID = %s"
            params.append(customer_id)
        if name:
            query += " AND customerName LIKE %s"
            params.append(f"%{name}%")
        if pid:
            query += " AND PID LIKE %s"
            params.append(f"%{pid}%")
        if min_age:
            query += " AND CAST(SUBSTRING(PID, 7, 4) AS UNSIGNED) <= YEAR(CURDATE()) - %s"
            params.append(min_age)
        if max_age:
            query += " AND CAST(SUBSTRING(PID, 7, 4) AS UNSIGNED) >= YEAR(CURDATE()) - %s"
            params.append(max_age)

        try:
            # 清空表格
            for item in self.customer_table.get_children():
                self.customer_table.delete(item)

            cursor = self.db_connection.cursor()
            cursor.execute(query, params)
            results = cursor.fetchall()

            for row in results:
                self.customer_table.insert("", tk.END, values=row)

            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"查询客户失败: {str(e)}")

    def load_customer_data(self):
        """加载客户数据"""
        try:
            # 清空表格
            for item in self.customer_table.get_children():
                self.customer_table.delete(item)

            cursor = self.db_connection.cursor()
            cursor.execute("SELECT * FROM userinfo")
            results = cursor.fetchall()

            for row in results:
                self.customer_table.insert("", tk.END, values=row)

            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"加载客户数据失败: {str(e)}")

    def add_customer(self):
        """添加客户"""
        dialog = bank_dialog.CustomerDialog(self)
        if dialog.result:
            self.load_customer_data()
            # 加载银行卡数据
            self.load_card_data()

    def edit_customer(self):
        """编辑客户"""
        selected = self.customer_table.selection()
        if not selected:
            messagebox.showwarning("选择错误", "请先选择一个客户！")
            return

        item = self.customer_table.item(selected[0])
        customer_id = item['values'][0]

        dialog = bank_dialog.CustomerDialog(self, customer_id)
        if dialog.result:
            self.load_customer_data()
            # 加载银行卡数据
            self.load_card_data()

    def delete_customer(self):
        """删除客户"""
        selected = self.customer_table.selection()
        if not selected:
            messagebox.showwarning("选择错误", "请先选择一个客户！")
            return

        item = self.customer_table.item(selected[0])
        customer_id = item['values'][0]

        if messagebox.askyesno("确认删除", f"确定要删除客户ID为 {customer_id} 的客户吗？"):
            try:
                cursor = self.db_connection.cursor()
                cursor.execute("DELETE FROM userinfo WHERE customerID = %s", (customer_id,))
                self.db_connection.commit()
                cursor.close()

                self.load_customer_data()
                # 加载银行卡数据
                self.load_card_data()
                messagebox.showinfo("成功", "客户删除成功！")
            except Exception as e:
                messagebox.showerror("数据库错误", f"删除客户失败: {str(e)}")

    def export_customer_csv(self):
        """导出客户CSV"""
        try:
            file_path = filedialog.asksaveasfilename(
                defaultextension=".csv",
                filetypes=[("CSV文件", "*.csv")],
                title="保存客户数据"
            )

            if not file_path:
                return

            with open(file_path, 'w', newline='', encoding='utf-8') as file:
                import csv
                writer = csv.writer(file)
                writer.writerow(['客户ID', '姓名', '身份证号', '联系电话', '联系地址'])

                cursor = self.db_connection.cursor()
                cursor.execute("SELECT * FROM userinfo")
                results = cursor.fetchall()

                for row in results:
                    writer.writerow(row)

                cursor.close()

            messagebox.showinfo("导出成功", f"客户数据已导出到 {file_path}！")
        except Exception as e:
            messagebox.showerror("导出失败", f"导出CSV文件失败: {str(e)}")

    def create_card_management(self, parent):
        """创建银行卡管理界面"""
        # 顶部按钮
        btn_frame = ttk.Frame(parent)
        btn_frame.pack(fill=tk.X, padx=10, pady=5)

        ttk.Button(btn_frame, text="添加银行卡", width=12, command=self.add_card, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="修改信息", width=10, command=self.edit_card, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="删除银行卡", width=12, command=self.delete_card, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="导出CSV", width=10, command=self.export_card_csv, style="Accent.TButton").pack(side=tk.LEFT, padx=5)

        # 查询框
        search_frame = ttk.Frame(parent)
        search_frame.pack(fill=tk.X, padx=10, pady=5)

        ttk.Label(search_frame, text="卡号:").pack(side=tk.LEFT, padx=5)
        self.card_id_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.card_id_var, width=15).pack(side=tk.LEFT, padx=5)

        ttk.Label(search_frame, text="客户ID:").pack(side=tk.LEFT, padx=5)
        self.card_customer_id_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.card_customer_id_var, width=15).pack(side=tk.LEFT, padx=5)

        ttk.Label(search_frame, text="余额范围:").pack(side=tk.LEFT, padx=5)
        self.balance_min_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.balance_min_var, width=10).pack(side=tk.LEFT, padx=5)
        ttk.Label(search_frame, text="至").pack(side=tk.LEFT, padx=5)
        self.balance_max_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.balance_max_var, width=10).pack(side=tk.LEFT, padx=5)

        ttk.Button(search_frame, text="查 询", width=10, command=self.search_card, style="Accent.TButton").pack(
            side=tk.LEFT, padx=5)

        # 表格
        table_frame = ttk.Frame(parent)
        table_frame.pack(expand=True, fill=tk.BOTH, padx=10, pady=5)

        columns = ("cardID", "curID", "savingID", "openDate", "openMoney",
                   "balance", "pass", "IsReportLoss", "customerID")
        self.card_table = ttk.Treeview(table_frame, columns=columns, show="headings")

        # 设置列标题
        self.card_table.heading("cardID", text="卡号")
        self.card_table.heading("curID", text="币种")
        self.card_table.heading("savingID", text="存款类型")
        self.card_table.heading("openDate", text="开户日期")
        self.card_table.heading("openMoney", text="开户金额")
        self.card_table.heading("balance", text="余额")
        self.card_table.heading("pass", text="密码")
        self.card_table.heading("IsReportLoss", text="是否挂失")
        self.card_table.heading("customerID", text="客户ID")

        # 设置列宽
        self.card_table.column("cardID", width=120, anchor=tk.CENTER)
        self.card_table.column("curID", width=60, anchor=tk.CENTER)
        self.card_table.column("savingID", width=80, anchor=tk.CENTER)
        self.card_table.column("openDate", width=120, anchor=tk.CENTER)
        self.card_table.column("openMoney", width=80, anchor=tk.CENTER)
        self.card_table.column("balance", width=80, anchor=tk.CENTER)
        self.card_table.column("pass", width=80, anchor=tk.CENTER)
        self.card_table.column("IsReportLoss", width=80, anchor=tk.CENTER)
        self.card_table.column("customerID", width=80, anchor=tk.CENTER)

        # 添加滚动条
        scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=self.card_table.yview)
        self.card_table.configure(yscroll=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.card_table.pack(expand=True, fill=tk.BOTH)

        # 加载数据
        self.load_card_data()

    def search_card(self):
        """查询银行卡"""
        card_id = self.card_id_var.get()
        customer_id = self.card_customer_id_var.get()
        balance_min = self.balance_min_var.get()
        balance_max = self.balance_max_var.get()

        query = "SELECT * FROM cardinfo WHERE 1=1"
        params = []

        if card_id:
            query += " AND cardID = %s"
            params.append(card_id)
        if customer_id:
            query += " AND customerID = %s"
            params.append(customer_id)
        if balance_min:
            query += " AND balance >= %s"
            params.append(balance_min)
        if balance_max:
            query += " AND balance <= %s"
            params.append(balance_max)

        try:
            # 清空表格
            for item in self.card_table.get_children():
                self.card_table.delete(item)

            cursor = self.db_connection.cursor()
            cursor.execute(query, params)
            results = cursor.fetchall()

            for row in results:
                self.card_table.insert("", tk.END, values=row)

            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"查询银行卡失败: {str(e)}")

    def load_card_data(self):
        """加载银行卡数据"""
        try:
            # 清空表格
            for item in self.card_table.get_children():
                self.card_table.delete(item)

            cursor = self.db_connection.cursor()
            cursor.execute("SELECT * FROM cardinfo")
            results = cursor.fetchall()

            for row in results:
                self.card_table.insert("", tk.END, values=row)

            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"加载银行卡数据失败: {str(e)}")

    def add_card(self):
        """添加银行卡"""
        dialog = bank_dialog.CardDialog(self)
        if dialog.result:
            # 验证卡号长度
            # card_id = dialog.card_id_var.get() if hasattr(dialog, 'card_id_var') else None
            # if card_id and len(card_id) != 16:
            #     messagebox.showwarning("输入错误", "卡号必须为16位数字！")
            #     return
            # # 验证密码长度
            # password = dialog.pass_var.get()
            # if len(password) != 6 or not password.isdigit():
            #     messagebox.showwarning("输入错误", "密码必须为6位数字！")
            #     return
            # # 验证开户金额
            # open_money = dialog.open_money_var.get()
            # if float(open_money) < 1:
            #     messagebox.showwarning("输入错误", "开户金额不能小于1元！")
            #     return
            self.load_card_data()

    def edit_card(self):
        """编辑银行卡信息"""
        selected = self.card_table.selection()
        if not selected:
            messagebox.showwarning("选择错误", "请先选择一张银行卡！")
            return

        item = self.card_table.item(selected[0])
        card_id = item['values'][0]

        dialog = bank_dialog.CardDialog(self, card_id)
        if dialog.result:
            # 验证卡号长度
            if len(str(card_id))!= 16:
                messagebox.showwarning("输入错误", "卡号必须为16位数字！")
                return
            # 验证密码长度
            password = dialog.pass_var.get()
            if len(password) != 6 or not password.isdigit():
                messagebox.showwarning("输入错误", "密码必须为6位数字！")
                return
            # 验证开户金额
            open_money = dialog.open_money_var.get()
            if float(open_money) < 1:
                messagebox.showwarning("输入错误", "开户金额不能小于1元！")
                return
            self.load_card_data()

    def delete_card(self):
        """删除银行卡"""
        selected = self.card_table.selection()
        if not selected:
            messagebox.showwarning("选择错误", "请先选择一张银行卡！")
            return

        item = self.card_table.item(selected[0])
        card_id = item['values'][0]

        if messagebox.askyesno("确认删除", f"确定要删除卡号为 {card_id} 的银行卡吗？"):
            try:
                cursor = self.db_connection.cursor()
                cursor.execute("DELETE FROM cardinfo WHERE cardID = %s", (card_id,))
                self.db_connection.commit()
                cursor.close()

                self.load_card_data()
                messagebox.showinfo("成功", "银行卡删除成功！")
            except Exception as e:
                messagebox.showerror("数据库错误", f"删除银行卡失败: {str(e)}")

    def export_card_csv(self):
        """导出银行卡CSV"""
        try:
            file_path = filedialog.asksaveasfilename(
                defaultextension=".csv",
                filetypes=[("CSV文件", "*.csv")],
                title="保存银行卡数据"
            )

            if not file_path:
                return

            with open(file_path, 'w', newline='', encoding='utf-8') as file:
                import csv
                writer = csv.writer(file)
                writer.writerow(
                    ['卡号', '币种', '存款类型', '开户日期', '开户金额', '余额', '密码', '是否挂失', '客户ID'])

                cursor = self.db_connection.cursor()
                cursor.execute("SELECT * FROM cardinfo")
                results = cursor.fetchall()

                for row in results:
                    writer.writerow(row)

                cursor.close()

            messagebox.showinfo("导出成功", f"银行卡数据已导出到 {file_path}！")
        except Exception as e:
            messagebox.showerror("导出失败", f"导出CSV文件失败: {str(e)}")

    def create_deposit_management(self, parent):
        """创建存款业务管理界面"""
        # 顶部按钮
        btn_frame = ttk.Frame(parent)
        btn_frame.pack(fill=tk.X, padx=10, pady=5)

        ttk.Button(btn_frame, text="添加存款类型", width=12, command=self.add_deposit, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="修改存款类型", width=12, command=self.edit_deposit, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="删除存款类型", width=12, command=self.delete_deposit, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="导出CSV", width=10, command=self.export_deposit_csv, style="Accent.TButton").pack(side=tk.LEFT, padx=5)

        # 表格
        table_frame = ttk.Frame(parent)
        table_frame.pack(expand=True, fill=tk.BOTH, padx=10, pady=5)

        columns = ("savingID", "savingName", "descrip")
        self.deposit_table = ttk.Treeview(table_frame, columns=columns, show="headings")

        # 设置列标题
        self.deposit_table.heading("savingID", text="存款ID")
        self.deposit_table.heading("savingName", text="存款名称")
        self.deposit_table.heading("descrip", text="存款描述")

        # 设置列宽
        self.deposit_table.column("savingID", width=80, anchor=tk.CENTER)
        self.deposit_table.column("savingName", width=150, anchor=tk.CENTER)
        self.deposit_table.column("descrip", width=300, anchor=tk.CENTER)

        # 添加滚动条
        scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=self.deposit_table.yview)
        self.deposit_table.configure(yscroll=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.deposit_table.pack(expand=True, fill=tk.BOTH)

        # 加载数据
        self.load_deposit_data()

    def load_deposit_data(self):
        """加载存款类型数据"""
        try:
            # 清空表格
            for item in self.deposit_table.get_children():
                self.deposit_table.delete(item)

            cursor = self.db_connection.cursor()
            cursor.execute("SELECT * FROM deposit")
            results = cursor.fetchall()

            for row in results:
                self.deposit_table.insert("", tk.END, values=row)

            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"加载存款类型数据失败: {str(e)}")

    def add_deposit(self):
        """添加存款类型"""
        dialog = bank_dialog.DepositDialog(self)
        if dialog.result:
            # 验证存款名称是否为空
            name = dialog.name_var.get()
            if not name:
                messagebox.showwarning("输入错误", "存款名称不能为空！")
                return
            self.load_deposit_data()

    def edit_deposit(self):
        """编辑存款类型"""
        selected = self.deposit_table.selection()
        if not selected:
            messagebox.showwarning("选择错误", "请先选择一个存款类型！")
            return

        item = self.deposit_table.item(selected[0])
        saving_id = item['values'][0]

        dialog = bank_dialog.DepositDialog(self, saving_id)
        if dialog.result:
            # 验证存款名称是否为空
            name = dialog.name_var.get()
            if not name:
                messagebox.showwarning("输入错误", "存款名称不能为空！")
                return
            self.load_deposit_data()

    def delete_deposit(self):
        """删除存款类型"""
        selected = self.deposit_table.selection()
        if not selected:
            messagebox.showwarning("选择错误", "请先选择一个存款类型！")
            return

        item = self.deposit_table.item(selected[0])
        saving_id = item['values'][0]

        if messagebox.askyesno("确认删除", f"确定要删除存款类型ID为 {saving_id} 的存款类型吗？"):
            try:
                cursor = self.db_connection.cursor()
                cursor.execute("DELETE FROM deposit WHERE savingID = %s", (saving_id,))
                self.db_connection.commit()
                cursor.close()

                self.load_deposit_data()
                messagebox.showinfo("成功", "存款类型删除成功！")
            except Exception as e:
                messagebox.showerror("数据库错误", f"删除存款类型失败: {str(e)}")

    def export_deposit_csv(self):
        """导出存款类型CSV"""
        try:
            file_path = filedialog.asksaveasfilename(
                defaultextension=".csv",
                filetypes=[("CSV文件", "*.csv")],
                title="保存存款类型数据"
            )

            if not file_path:
                return

            with open(file_path, 'w', newline='', encoding='utf-8') as file:
                import csv
                writer = csv.writer(file)
                writer.writerow(['存款ID', '存款名称', '存款描述'])

                cursor = self.db_connection.cursor()
                cursor.execute("SELECT * FROM deposit")
                results = cursor.fetchall()

                for row in results:
                    writer.writerow(row)

                cursor.close()

            messagebox.showinfo("导出成功", f"存款类型数据已导出到 {file_path}！")
        except Exception as e:
            messagebox.showerror("导出失败", f"导出CSV文件失败: {str(e)}")

    def create_transaction_management(self, parent):
        """创建交易管理界面"""
        # 顶部按钮
        btn_frame = ttk.Frame(parent)
        btn_frame.pack(fill=tk.X, padx=10, pady=5)

        ttk.Button(btn_frame, text="删除记录", width=10, command=self.delete_transaction, style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="导出CSV", width=10, command=self.export_transaction_csv, style="Accent.TButton").pack(side=tk.LEFT, padx=5)

        # 查询框
        search_frame = ttk.Frame(parent)
        search_frame.pack(fill=tk.X, padx=10, pady=5)
        ttk.Label(search_frame, text="交易ID:").pack(side=tk.LEFT, padx=5)
        self.trade_id_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.trade_id_var, width=15).pack(side=tk.LEFT, padx=5)

        ttk.Label(search_frame, text="卡号:").pack(side=tk.LEFT, padx=5)
        self.trade_card_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.trade_card_var, width=15).pack(side=tk.LEFT, padx=5)

        ttk.Label(search_frame, text="交易类型:").pack(side=tk.LEFT, padx=5)
        self.trade_type_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.trade_type_var, width=15).pack(side=tk.LEFT, padx=5)

        ttk.Label(search_frame, text="交易金额范围:").pack(side=tk.LEFT, padx=5)
        self.trade_money_min_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.trade_money_min_var, width=10).pack(side=tk.LEFT, padx=5)
        ttk.Label(search_frame, text="至").pack(side=tk.LEFT, padx=5)
        self.trade_money_max_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.trade_money_max_var, width=10).pack(side=tk.LEFT, padx=5)
        ttk.Button(search_frame, text="查 询", width=10, command=self.search_transaction, style="Accent.TButton").pack(
            side=tk.LEFT, padx=5)

        # 表格
        table_frame = ttk.Frame(parent)
        table_frame.pack(expand=True, fill=tk.BOTH, padx=10, pady=5)

        columns = ("tradeID", "tradeDate", "tradeType", "cardID", "tradeMoney", "remark")
        self.transaction_table = ttk.Treeview(table_frame, columns=columns, show="headings")

        # 设置列标题
        self.transaction_table.heading("tradeID", text="交易ID")
        self.transaction_table.heading("tradeDate", text="交易日期")
        self.transaction_table.heading("tradeType", text="交易类型")
        self.transaction_table.heading("cardID", text="卡号")
        self.transaction_table.heading("tradeMoney", text="交易金额")
        self.transaction_table.heading("remark", text="备注")

        # 设置列宽
        self.transaction_table.column("tradeID", width=80, anchor=tk.CENTER)
        self.transaction_table.column("tradeDate", width=150, anchor=tk.CENTER)
        self.transaction_table.column("tradeType", width=100, anchor=tk.CENTER)
        self.transaction_table.column("cardID", width=120, anchor=tk.CENTER)
        self.transaction_table.column("tradeMoney", width=100, anchor=tk.CENTER)
        self.transaction_table.column("remark", width=250, anchor=tk.CENTER)

        # 添加滚动条
        scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=self.transaction_table.yview)
        self.transaction_table.configure(yscroll=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.transaction_table.pack(expand=True, fill=tk.BOTH)

        # 加载数据
        self.load_transaction_data()

    def search_transaction(self):
        """查询交易记录"""
        trade_id = self.trade_id_var.get()
        card_id = self.trade_card_var.get()
        trade_type = self.trade_type_var.get()
        money_min = self.trade_money_min_var.get()
        money_max = self.trade_money_max_var.get()

        query = "SELECT * FROM tradeinfo WHERE 1=1"
        params = []

        if trade_id:
            query += " AND tradeID = %s"
            params.append(trade_id)
        if card_id:
            query += " AND cardID = %s"
            params.append(card_id)
        if trade_type:
            query += " AND tradeType LIKE %s"
            params.append(f"%{trade_type}%")
        if money_min:
            query += " AND tradeMoney >= %s"
            params.append(money_min)
        if money_max:
            query += " AND tradeMoney <= %s"
            params.append(money_max)

        try:
            # 清空表格
            for item in self.transaction_table.get_children():
                self.transaction_table.delete(item)

            cursor = self.db_connection.cursor()
            cursor.execute(query, params)
            results = cursor.fetchall()

            for row in results:
                self.transaction_table.insert("", tk.END, values=row)

            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"查询交易记录失败: {str(e)}")

    def delete_transaction(self):
        """删除交易记录"""
        selected = self.transaction_table.selection()
        if not selected:
            messagebox.showwarning("选择错误", "请先选择一条交易记录！")
            return

        item = self.transaction_table.item(selected[0])
        trade_id = item['values'][0]

        if messagebox.askyesno("确认删除", f"确定要删除交易ID为 {trade_id} 的交易记录吗？"):
            try:
                cursor = self.db_connection.cursor()
                cursor.execute("DELETE FROM tradeinfo WHERE tradeID = %s", (trade_id,))
                self.db_connection.commit()
                cursor.close()

                self.load_transaction_data()
                messagebox.showinfo("成功", "交易记录删除成功！")
            except Exception as e:
                messagebox.showerror("数据库错误", f"删除交易记录失败: {str(e)}")

    def export_transaction_csv(self):
        """导出交易数据CSV"""
        try:
            file_path = filedialog.asksaveasfilename(
                defaultextension=".csv",
                filetypes=[("CSV文件", "*.csv")],
                title="保存交易数据"
            )

            if not file_path:
                return

            with open(file_path, 'w', newline='', encoding='utf-8') as file:
                import csv
                writer = csv.writer(file)
                writer.writerow(['交易ID', '交易日期', '交易类型', '卡号', '交易金额', '备注'])

                cursor = self.db_connection.cursor()
                cursor.execute("SELECT * FROM tradeinfo")
                results = cursor.fetchall()

                for row in results:
                    writer.writerow(row)

                cursor.close()

            messagebox.showinfo("导出成功", f"交易数据已导出到 {file_path}！")
        except Exception as e:
            messagebox.showerror("导出失败", f"导出CSV文件失败: {str(e)}")

    def load_transaction_data(self):
        """加载交易数据"""
        try:
            # 清空表格
            for item in self.transaction_table.get_children():
                self.transaction_table.delete(item)

            cursor = self.db_connection.cursor()
            cursor.execute("SELECT * FROM tradeinfo")
            results = cursor.fetchall()

            for row in results:
                self.transaction_table.insert("", tk.END, values=row)

            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"加载交易数据失败: {str(e)}")

    def create_account_operations(self, parent):
        """创建账户操作界面"""
        # 主框架
        main_frame = ttk.Frame(parent)
        main_frame.pack(expand=True, fill=tk.BOTH, padx=20, pady=20)

        # 账户信息组
        info_group = ttk.LabelFrame(main_frame, text="账户信息", padding=10)
        info_group.pack(fill=tk.X, padx=10, pady=10)

        # 获取账户信息
        try:
            cursor = self.db_connection.cursor()
            cursor.execute("SELECT * FROM cardinfo WHERE cardID = %s", (self.card_id,))
            card_info = cursor.fetchone()
            cursor.close()

            if not card_info:
                messagebox.showerror("错误", "无法获取银行卡信息！")
                return

            self.current_balance = float(card_info[5])
            self.card_status = "已挂失" if card_info[7] == "是" else "正常"

            # 显示账户信息
            info_frame = ttk.Frame(info_group)
            info_frame.pack(fill=tk.X, padx=5, pady=5)

            ttk.Label(info_frame, text="卡号:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.W)
            ttk.Label(info_frame, text=card_info[0], font=("", 10, "bold")).grid(row=0, column=1, padx=5, pady=5,
                                                                                 sticky=tk.W)

            ttk.Label(info_frame, text="余额:").grid(row=1, column=0, padx=5, pady=5, sticky=tk.W)
            self.balance_label = ttk.Label(info_frame, text=f"¥{self.current_balance:.2f}",
                                           font=("", 10, "bold"), foreground="#1890ff")
            self.balance_label.grid(row=1, column=1, padx=5, pady=5, sticky=tk.W)

            ttk.Label(info_frame, text="状态:").grid(row=2, column=0, padx=5, pady=5, sticky=tk.W)
            status_color = "green" if self.card_status == "正常" else "red"
            self.status_label = ttk.Label(info_frame, text=self.card_status,
                                          font=("", 10, "bold"), foreground=status_color)
            self.status_label.grid(row=2, column=1, padx=5, pady=5, sticky=tk.W)

        except Exception as e:
            messagebox.showerror("数据库错误", f"获取银行卡信息失败: {str(e)}")
            return

        # 操作组
        operation_group = ttk.LabelFrame(main_frame, text="账户操作", padding=10)
        operation_group.pack(fill=tk.BOTH, padx=10, pady=10, expand=True)

        # 存款
        deposit_frame = ttk.Frame(operation_group)
        deposit_frame.pack(fill=tk.X, padx=5, pady=5)

        ttk.Label(deposit_frame, text="存款金额:").pack(side=tk.LEFT, padx=5)
        self.deposit_amount = ttk.Entry(deposit_frame, width=15)
        self.deposit_amount.pack(side=tk.LEFT, padx=5)
        self.deposit_btn = ttk.Button(deposit_frame, text="存 款", command=self.deposit, style="Accent.TButton")
        self.deposit_btn.pack(side=tk.LEFT, padx=5)

        # 取款
        withdraw_frame = ttk.Frame(operation_group)
        withdraw_frame.pack(fill=tk.X, padx=5, pady=5)

        ttk.Label(withdraw_frame, text="取款金额:").pack(side=tk.LEFT, padx=5)
        self.withdraw_amount = ttk.Entry(withdraw_frame, width=15)
        self.withdraw_amount.pack(side=tk.LEFT, padx=5)
        self.withdraw_btn = ttk.Button(withdraw_frame, text="取 款", command=self.withdraw, style="Accent.TButton")
        self.withdraw_btn.pack(side=tk.LEFT, padx=5)

        # 转账
        transfer_frame = ttk.Frame(operation_group)
        transfer_frame.pack(fill=tk.X, padx=5, pady=5)

        ttk.Label(transfer_frame, text="对方卡号:").pack(side=tk.LEFT, padx=5)
        self.transfer_card = ttk.Entry(transfer_frame, width=15)
        self.transfer_card.pack(side=tk.LEFT, padx=5)

        ttk.Label(transfer_frame, text="转账金额:").pack(side=tk.LEFT, padx=5)
        self.transfer_amount = ttk.Entry(transfer_frame, width=15)
        self.transfer_amount.pack(side=tk.LEFT, padx=5)
        self.transfer_btn = ttk.Button(transfer_frame, text="转 账", command=self.transfer, style="Accent.TButton")
        self.transfer_btn.pack(side=tk.LEFT, padx=5)

        # 根据银行卡状态更新按钮状态
        self.update_operation_buttons()

    def update_operation_buttons(self):
        """根据银行卡状态更新按钮状态"""
        if self.card_status == "已挂失":
            self.deposit_btn.config(state=tk.DISABLED)
            self.withdraw_btn.config(state=tk.DISABLED)
            self.transfer_btn.config(state=tk.DISABLED)
        else:
            self.deposit_btn.config(state=tk.NORMAL)
            self.withdraw_btn.config(state=tk.NORMAL)
            self.transfer_btn.config(state=tk.NORMAL)

    def deposit(self):
        """存款操作"""
        if self.card_status == "已挂失":
            messagebox.showwarning("操作失败", "银行卡已挂失，无法进行存款操作！")
            return

        amount_str = self.deposit_amount.get()
        if not amount_str:
            messagebox.showwarning("输入错误", "请输入存款金额！")
            return

        try:
            amount = float(amount_str)
            if amount <= 0:
                messagebox.showwarning("输入错误", "存款金额必须大于0！")
                return
        except ValueError:
            messagebox.showwarning("输入错误", "请输入有效的金额！")
            return

        try:
            cursor = self.db_connection.cursor()

            # 更新余额
            cursor.execute("UPDATE cardinfo SET balance = balance + %s WHERE cardID = %s", (amount, self.card_id))
            self.db_connection.commit()

            # 更新余额
            cursor.execute("SELECT balance FROM cardinfo WHERE cardID = %s", (self.card_id,))
            new_balance = cursor.fetchone()[0]
            self.current_balance = float(new_balance)
            self.balance_label.config(text=f"¥{self.current_balance:.2f}")

            # 加载最新的交易记录
            self.load_user_transactions()

            cursor.close()

            self.deposit_amount.delete(0, tk.END)
            messagebox.showinfo("成功", "存款操作成功！")
        except Exception as e:
            messagebox.showerror("操作失败", f"存款操作失败: {str(e)}")

    def withdraw(self):
        """取款操作"""
        if self.card_status == "已挂失":
            messagebox.showwarning("操作失败", "银行卡已挂失，无法进行取款操作！")
            return

        amount_str = self.withdraw_amount.get()
        if not amount_str:
            messagebox.showwarning("输入错误", "请输入取款金额！")
            return

        try:
            amount = float(amount_str)
            if amount <= 0:
                messagebox.showwarning("输入错误", "取款金额必须大于0！")
                return
        except ValueError:
            messagebox.showwarning("输入错误", "请输入有效的金额！")
            return

        try:
            cursor = self.db_connection.cursor()

            # 检查余额是否足够
            cursor.execute("SELECT balance FROM cardinfo WHERE cardID = %s", (self.card_id,))
            current_balance = cursor.fetchone()[0]
            if current_balance < amount:
                messagebox.showwarning("错误", "余额不足！")
                return

            # 更新余额
            cursor.execute("UPDATE cardinfo SET balance = balance - %s WHERE cardID = %s", (amount, self.card_id))
            self.db_connection.commit()

            # 更新余额显示
            cursor.execute("SELECT balance FROM cardinfo WHERE cardID = %s", (self.card_id,))
            new_balance = cursor.fetchone()[0]
            self.current_balance = float(new_balance)
            self.balance_label.config(text=f"¥{self.current_balance:.2f}")

            # 加载最新的交易记录
            self.load_user_transactions()

            cursor.close()

            self.withdraw_amount.delete(0, tk.END)
            messagebox.showinfo("成功", "取款操作成功！")
        except Exception as e:
            messagebox.showerror("操作失败", f"取款操作失败: {str(e)}")

    def transfer(self):
        """转账操作"""
        if self.card_status == "已挂失":
            messagebox.showwarning("操作失败", "银行卡已挂失，无法进行转账操作！")
            return

        target_card = self.transfer_card.get()
        amount_str = self.transfer_amount.get()

        if not target_card or not amount_str:
            messagebox.showwarning("输入错误", "请填写对方卡号和转账金额！")
            return

        try:
            amount = float(amount_str)
            if amount <= 0:
                messagebox.showwarning("输入错误", "转账金额必须大于0！")
                return
        except ValueError:
            messagebox.showwarning("输入错误", "请输入有效的金额！")
            return

        if target_card == self.card_id:
            messagebox.showwarning("输入错误", "不能转账给自己！")
            return

        try:
            cursor = self.db_connection.cursor()

            # 检查目标卡号是否存在
            cursor.execute("SELECT COUNT(*) FROM cardinfo WHERE cardID = %s", (target_card,))
            if cursor.fetchone()[0] == 0:
                messagebox.showwarning("错误", "对方卡号不存在！")
                return

            # 检查余额是否足够
            cursor.execute("SELECT balance FROM cardinfo WHERE cardID = %s", (self.card_id,))
            current_balance = cursor.fetchone()[0]
            if current_balance < amount:
                messagebox.showwarning("错误", "余额不足！")
                return

            # 转账逻辑，直接更新转出方和转入方的余额
            cursor.execute("UPDATE cardinfo SET balance = balance - %s WHERE cardID = %s", (amount, self.card_id))
            cursor.execute("UPDATE cardinfo SET balance = balance + %s WHERE cardID = %s", (amount, target_card))

            self.db_connection.commit()

            # 更新余额
            cursor.execute("SELECT balance FROM cardinfo WHERE cardID = %s", (self.card_id,))
            new_balance = cursor.fetchone()[0]
            self.current_balance = float(new_balance)
            self.balance_label.config(text=f"¥{self.current_balance:.2f}")

            # 加载最新的交易记录
            self.load_user_transactions()

            cursor.close()

            self.transfer_card.delete(0, tk.END)
            self.transfer_amount.delete(0, tk.END)
            messagebox.showinfo("成功", "转账操作成功！")
        except Exception as e:
            messagebox.showerror("操作失败", f"转账操作失败: {str(e)}")

    def create_transaction_query(self, parent):
        """创建交易查询界面"""
        # 表格
        table_frame = ttk.Frame(parent)
        table_frame.pack(expand=True, fill=tk.BOTH, padx=10, pady=5)

        columns = ("tradeID", "tradeDate", "tradeType", "tradeMoney", "remark")
        self.transaction_table = ttk.Treeview(table_frame, columns=columns, show="headings")

        # 设置列标题
        self.transaction_table.heading("tradeID", text="交易ID")
        self.transaction_table.heading("tradeDate", text="交易日期")
        self.transaction_table.heading("tradeType", text="交易类型")
        self.transaction_table.heading("tradeMoney", text="交易金额")
        self.transaction_table.heading("remark", text="备注")

        # 设置列宽
        self.transaction_table.column("tradeID", width=80, anchor=tk.CENTER)
        self.transaction_table.column("tradeDate", width=150, anchor=tk.CENTER)
        self.transaction_table.column("tradeType", width=100, anchor=tk.CENTER)
        self.transaction_table.column("tradeMoney", width=100, anchor=tk.CENTER)
        self.transaction_table.column("remark", width=250, anchor=tk.CENTER)

        # 添加滚动条
        scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=self.transaction_table.yview)
        self.transaction_table.configure(yscroll=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.transaction_table.pack(expand=True, fill=tk.BOTH)

        # 加载数据
        self.load_user_transactions()

    def load_user_transactions(self):
        """加载用户交易数据"""
        try:
            # 清空表格
            for item in self.transaction_table.get_children():
                self.transaction_table.delete(item)

            cursor = self.db_connection.cursor()
            cursor.execute("SELECT tradeID, tradeDate, tradeType, tradeMoney, remark FROM tradeinfo WHERE cardID = %s",
                           (self.card_id,))
            results = cursor.fetchall()

            for row in results:
                self.transaction_table.insert("", tk.END, values=row)

            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"加载交易数据失败: {str(e)}")

    def create_account_management(self, parent):
        """创建账户管理界面"""
        # 主框架
        main_frame = ttk.Frame(parent)
        main_frame.pack(expand=True, fill=tk.BOTH, padx=20, pady=20)

        # 账户管理组
        manage_group = ttk.LabelFrame(main_frame, text="账户管理", padding=20)
        manage_group.pack(fill=tk.X, padx=10, pady=10)

        # 挂失/解挂
        report_frame = ttk.Frame(manage_group)
        report_frame.pack(fill=tk.X, padx=5, pady=10)

        # 获取当前状态
        try:
            cursor = self.db_connection.cursor()
            cursor.execute("SELECT IsReportLoss FROM cardinfo WHERE cardID = %s", (self.card_id,))
            current_status = cursor.fetchone()[0]
            cursor.close()

            self.report_btn = ttk.Button(report_frame, text="挂失账户" if current_status == "否" else "解除挂失",
                                         command=self.toggle_account_status,
                                         style="Accent.TButton")
            self.report_btn.pack(side=tk.LEFT, padx=5)

        except Exception as e:
            messagebox.showerror("数据库错误", f"获取账户状态失败: {str(e)}")

        # 修改密码
        pass_frame = ttk.Frame(manage_group)
        pass_frame.pack(fill=tk.X, padx=5, pady=10)

        ttk.Label(pass_frame, text="新密码:").pack(side=tk.LEFT, padx=5)
        self.new_pass = ttk.Entry(pass_frame, width=20, show="*")
        self.new_pass.pack(side=tk.LEFT, padx=5)
        ttk.Button(pass_frame, text="修改密码", command=self.change_password, style="Accent.TButton").pack(side=tk.LEFT, padx=5)

    def toggle_account_status(self):
        """切换账户状态（挂失/解挂）"""
        try:
            cursor = self.db_connection.cursor()

            # 获取当前状态
            cursor.execute("SELECT IsReportLoss FROM cardinfo WHERE cardID = %s", (self.card_id,))
            current_status = cursor.fetchone()[0]
            new_status = "是" if current_status == "否" else "否"

            # 更新状态
            cursor.execute("UPDATE cardinfo SET IsReportLoss = %s WHERE cardID = %s",
                           (new_status, self.card_id))
            self.db_connection.commit()

            # 更新按钮文本
            self.report_btn.config(text="挂失账户" if new_status == "否" else "解除挂失")

            # 更新状态变量
            self.card_status = "已挂失" if new_status == "是" else "正常"

            # 更新界面状态
            self.status_label.config(text=self.card_status,
                                     foreground="red" if self.card_status == "已挂失" else "green")

            # 更新操作按钮状态
            self.update_operation_buttons()

            cursor.close()

            message = f"账户已{'挂失' if new_status == '是' else '解除挂失'}！"
            messagebox.showinfo("成功", message)
        except Exception as e:
            messagebox.showerror("操作失败", f"更新账户状态失败: {str(e)}")

    def change_password(self):
        """修改密码"""
        new_pass = self.new_pass.get()
        if not new_pass:
            messagebox.showwarning("输入错误", "请输入新密码！")
            return

        try:
            cursor = self.db_connection.cursor()
            cursor.execute("UPDATE cardinfo SET pass = %s WHERE cardID = %s",
                           (new_pass, self.card_id))
            self.db_connection.commit()
            cursor.close()

            self.new_pass.delete(0, tk.END)
            messagebox.showinfo("成功", "密码修改成功！")
        except Exception as e:
            messagebox.showerror("操作失败", f"修改密码失败: {str(e)}")

    def logout(self):
        """注销登录"""
        self.main_frame.pack_forget()
        self.create_login_ui()